package com.woniuxy.controller;

import com.woniuxy.entity.Dynamic;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.entity.Venue;
import com.woniuxy.service.DynamicService;
import com.woniuxy.utils.CodeUtils;
import com.woniuxy.utils.LoginRegister;
import com.woniuxy.utils.RegexUtils;
import com.woniuxy.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/dynamic")
public class DynamicController {

    @Autowired
    private DynamicService dynamicService;

    /**
     * 所有该场馆的好友的朋友圈
     * @param vid 场馆id
     * @return ResponseEntity
     */
    @GetMapping("/allOfVenue/{vid}")
    public ResponseEntity<List<Dynamic>> findAllDynamicsByVid(@PathVariable("vid") int vid){
        ResponseEntity<List<Dynamic>> listResponseEntity = new ResponseEntity<>();
        List<Dynamic> allDynamicsByVid = dynamicService.findAllDynamicsByVid(vid);
        if (allDynamicsByVid!=null){
            return listResponseEntity.setMsg("你的朋友圈").setCode(CodeUtils.SUCCESS_CODE).setData(allDynamicsByVid);
        }
        return listResponseEntity.setMsg("出大问题").setCode(CodeUtils.ERROR_CODE);
    }

    /**
     * 添加一条朋友圈
     * @param dynamic 动态
     * @return ResponseEntity<Void>
     */
    @PostMapping("/add")
    public ResponseEntity<Void> addDynamic(@RequestBody Dynamic dynamic){
        ResponseEntity<Void> addVoidResponseEntity = new ResponseEntity<>();
        if (dynamic==null){
            return addVoidResponseEntity.setMsg("空数据").setCode(CodeUtils.ERROR_CODE);
        }
        dynamic.setSendTime(TimeUtils.getNowTime());
        if (dynamicService.addNewDynamic(dynamic)== LoginRegister.OPERATION_SUCCESS){
            return addVoidResponseEntity.setCode(CodeUtils.SUCCESS_CODE).setMsg("添加成功");
        }
        return addVoidResponseEntity.setMsg("添加失败").setCode(CodeUtils.ERROR_CODE);
    }

    /**
     * 上传朋友圈的配图
     * @param imageName 图片名
     * @param imageFile 图片文件
     * @return ResponseEntity
     * @throws IOException
     */
    @PostMapping("/image")
    public ResponseEntity<Void> downloadImages(@RequestParam("name") String imageName, @RequestParam("data") MultipartFile imageFile, HttpServletRequest request) throws IOException {
        ResponseEntity<Void> fileResponseEntity = new ResponseEntity<>();
        System.out.println(imageName);
        System.out.println(imageFile);
        if (imageFile.isEmpty()) {
            return fileResponseEntity.setMsg("文件为空").setCode(CodeUtils.ERROR_CODE);
        }
        // 获取文件名
        String fileName = imageFile.getOriginalFilename();
        System.out.println("上传的文件名为:" + fileName);
        if (!RegexUtils.photoIsRight(fileName)){
            return ResponseEntity.ERROR.setMsg("请上传正确的图片格式");
        }
        // 获取文件的后缀名
        String suffixName="";
        if (fileName!=null&&fileName.lastIndexOf(".")!=-1){
            suffixName= fileName.substring(fileName.lastIndexOf("."));
            System.out.println("上传的后缀名为:" + suffixName);
        }
        //获取项目根路径
        String path = request.getServletContext().getRealPath("");
        File root = new File(path);
        File main= root.getParentFile();
        File fileDir = new File(main, "resources/static/images");
        // 得到文件存储的路径 files/文件名
        String imageMing = UUID.randomUUID() + suffixName;
//        System.out.println("即将存入硬盘和数据库的图片名："+imageMing);
        if (!fileDir.exists()) {
            fileDir.mkdirs(); // 创建
        }
        HttpSession session = request.getSession();
        Venue venue = (Venue)session.getAttribute("venue");
        int vid=venue.getVid();
        System.out.println("即将存入数据库的图片名："+imageMing);
        Dynamic dynamic = new Dynamic().setSender(vid).setImage("../images/"+imageMing);
        imageMing = fileDir.getAbsolutePath() + File.separator + imageMing;
        System.out.println("即将存入硬盘的图片名："+imageMing);
        File dest = new File(imageMing);
        imageFile.transferTo(dest);
        //存入数据库根据该最新发布的动态加图片
        if (dynamicService.updateImageByDynamic(dynamic)==LoginRegister.OPERATION_SUCCESS){
            return fileResponseEntity.setMsg("上传朋友圈图片成功").setCode(CodeUtils.SUCCESS_CODE);
        }
        return fileResponseEntity.setMsg("上传朋友圈图片失败").setCode(CodeUtils.ERROR_CODE);
    }

}
